package com.cos.web.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author: COS
 * @time: 2021/11/17 16:04
 * @description:
 */
@Controller
@RequestMapping("/file")
public class FileController {
    @RequestMapping("/upload")
    public void upload(MultipartFile files, HttpServletRequest request,String username) throws IOException {
        System.out.println(files.getOriginalFilename());
        System.out.println(files.getName());
        System.out.println(files.getSize());
        System.out.println(files.getContentType());
        //处理文件同名覆盖
        String newFileName = UUID.randomUUID().toString().replace("-", "") + "_" + files.getOriginalFilename();
        System.out.println("username:"+username);
        String realPath = request.getServletContext().getRealPath("/upload");
        File f = new File(realPath);
        if (!f.exists()) {
            f.mkdir();
        }
//        File[] files1 = f.listFiles();
//        for (File file : files1) {
//            if (file.isDirectory()){
//                //递归
//            }else{
//                //保存数据到集合
//            }
//        }


        //传输复制文件到本地服务器
        files.transferTo(new File(realPath+"\\"+files.getOriginalFilename()));
    }
    @RequestMapping("/download")
    public void downLoad(HttpSession session, HttpServletResponse response, String fileName) throws IOException {
        String realPath = session.getServletContext().getRealPath("/upload");
        //响应头 设置响应是附件下载,而不是浏览器解析展示
        response.setHeader("content-disposition","attachment;filename="+fileName);
        IOUtils.copy(new FileInputStream(realPath+"\\"+fileName),response.getOutputStream());
    }

}
